package com.beta.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.beta.em.order.TransactionType;
import com.beta.entity.OltpTxnLogs;
import com.beta.entity.OrderSettleQueues;
import com.beta.entity.Orders;
import com.beta.entity.Users;
import com.beta.mapper.OltpTxnLogsMapper;
import com.beta.service.IOltpTxnLogsService;
import com.beta.service.IOrderSettleQueuesService;
import com.beta.service.IDateTimeService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 *
 * OltpTxnLogs 表数据服务层接口实现类
 *
 */
@Service
public class OltpTxnLogsService extends SuperServiceImpl<OltpTxnLogsMapper, OltpTxnLogs> implements IOltpTxnLogsService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IDateTimeService dateTimeService;
    @Autowired
    private IOrderSettleQueuesService settledQueuesService;

    @Override
    public void logUserTransaction(Orders order, Users users, TransactionType txnType, BigDecimal amount, BigDecimal balance) {
        logger.info("用户交易流水 <== order:{}, user:{}, type:{}, amount:{}, balance:{}",
                order.getCode(), users.getUsername(), txnType.getValue(), amount, balance);
        Date dbDate = dateTimeService.toDbDate();
        OltpTxnLogs oltpTxnLogs = new OltpTxnLogs()
                .setUserId(users.getId())
                .setUsername(users.getUsername())
                .setUserPhone(users.getPhone())
                .setUserType(users.getUserType())
                .setOrderId(order.getId())
                .setOrderCode(order.getCode())
                .setLedgerCode(users.getLedgerCode())
                .setAmount(amount)
                .setBalance(balance)
                .setCreatedAt(dbDate)
                .setUpdatedAt(dbDate)
                .setTxnDate(dbDate)
                .setTxnType(txnType.getValue());
        insertSelective(oltpTxnLogs);
//        onInsert(txnType, oltpTxnLogs);
    }

    @Override
    public void logPlatformTransaction(Orders order, TransactionType txnType, BigDecimal amount, BigDecimal balance) {
        logger.info("平台交易流水 <== order:{}, user:{}, type:{}, amount:{}, balance:{}",
                order.getCode(), "platform", txnType.getValue(), amount, balance);
        Date dbDate = dateTimeService.toDbDate();
        OltpTxnLogs oltpTxnLogs = new OltpTxnLogs()
//                .setUserId(users.getId())
//                .setUsername(users.getUsername())
//                .setUserType(users.getUserType())
                .setOrderId(order.getId())
                .setOrderCode(order.getCode())
//                .setLedgerCode(users.getLedgerCode())
                .setAmount(amount)
                .setBalance(balance)
                .setCreatedAt(dbDate)
                .setUpdatedAt(dbDate)
                .setTxnDate(dbDate)
                .setTxnType(txnType.getValue());
        insertSelective(oltpTxnLogs);
//        onInsert(txnType, oltpTxnLogs);
    }

    @Override
    public List<OltpTxnLogs> getUserOrderLogs(Integer userId, Integer ordersId, List<String> txnTypes) {
        if (CollectionUtils.isEmpty(txnTypes)) {
            return Collections.emptyList();
        }

        return baseMapper.selectUserOrderLogs(userId, ordersId, txnTypes);
    }

    @Override
    public List<OltpTxnLogs> getLogByOrderAndTxnType(Integer orderId, TransactionType txnType) {
        return selectList(new EntityWrapper<>(new OltpTxnLogs().setOrderId(orderId).setTxnType(txnType.getValue())));
    }

    // 监听插入事件，用于写入清算队列数据
    private void onInsert(TransactionType txnType, OltpTxnLogs oltpTxnLogs) {
        if (TransactionType.SETTLED.equals(txnType) || TransactionType.REFUND_SETTLED.equals(txnType)) {
            addToSettleQueue(oltpTxnLogs);
        }
    }

    private void addToSettleQueue(OltpTxnLogs oltpTxnLogs) {
        Date dbDate = dateTimeService.toDbDate();
        OrderSettleQueues orderSettleQueues = new OrderSettleQueues()
                .setUserId(oltpTxnLogs.getUserId())
                .setUsername(oltpTxnLogs.getUsername())
                .setUserPhone(oltpTxnLogs.getUserPhone())
                .setUserType(oltpTxnLogs.getUserType())
                .setLedgerCode(oltpTxnLogs.getLedgerCode())
                .setTxnType(oltpTxnLogs.getTxnType())
                .setAmount(oltpTxnLogs.getAmount())
                .setOrderId(oltpTxnLogs.getOrderId())
                .setOrderCode(oltpTxnLogs.getOrderCode())
                .setTxnDate(oltpTxnLogs.getTxnDate())
                .setCreatedAt(dbDate)
                .setUpdatedAt(dbDate);
        settledQueuesService.insertSelective(orderSettleQueues);
    }
}